<script>
    $(function(){
        let callid='',
            nowPhone='',
            http_url=$('.http_url').val(),
            wsUrl=$('.wss_url').val(),
            ws='',
            callStatus='init',
            fromOtherPageNumber= sessionStorage.getItem('callNumber'),
            calljumpInfo= sessionStorage.getItem('calljumpInfo'),
            callOut_timer=null,
            callIn_timer=null;

        async function ajaxPromise(json) {
            return new Promise((resolve) => {
                $.ajax({
                    url: json.url,
                    method: json.method,
                    data: json.data,
                    success:function(res){
                        resolve(res);
                    }
                })
            });
        }
        
        {if $workerId}
            initPing();
        {/if}
        $('body')
        //打开软电话软件
        .on('click','[data-fn="open-ztphone"]',function(){
            location.href = 'ztphone://';
        })
        //轮播点呼出
        .on('click','[data-fn="callout"]',function(){
            let number=$(this).attr('data-telephone');
            callFunction(number);
        })
        // 下拉点呼出
        .on('click','[data-fn="hover-call"]',function(){
            let number=$(this).attr('data-telephone');
            $('.phone-dropdown').hide(); 
            callFunction(number);
        })
        //挂断
        .on('click','[data-fn="hangup"]',function(){
            hangupFunction();
        })
        //呼入接听
        .on('click','[data-fn="answer"]',function(){
            answerFunction();
        })
        //呼入查询案件信息
        .on('click','[data-fn="callIn-searchBtn"]',function(){
            searchCasein($('[data-ele="callIn-seacth-input"]').val());
        })
        //接听面板跳详情页
        .on('click','[data-ele="jump-detal"]',function(){
            sessionStorage.setItem('calljumpInfo',JSON.stringify({
                phone: $(this).attr('data-telephone'),
                callInTimer: $('.callInTimer').html(),
                callid:  $(this).attr('data-callid'),
            }));
            communicateCall({
                phone: $(this).attr('data-telephone'),
                callid:  $(this).attr('data-callid'),
                caseId: $(this).attr('data-caseId'),
            })
        })

        async function initPing(){
            $.ajax({
                url: http_url+'/ping',
                method: "get",
                timeout: 1000,
                data:{},
                success:function(res){
                    if(res.code==200){
                        if(res.regstatus=='-1'){
                            ws='';
                            window.ws=ws;
                            $('.user-name-word').html('<span data-fn="open-ztphone">请先注册软化机</span>');
                            $('[data-ele="busy-icon"]').show().siblings().hide();
                            setTimeout(()=>{
                                initPing();
                            },2000)
                        }else{
                            //正常
                            $('.user-name-word').html($('.user-name-word').attr('data-num'));
                            $('[data-ele="normal-icon"]').show().siblings().hide();
                            $('[data-fn="callout"]').show();
                            createWebSocket();
                            //列表页点击号码进入详情页自动呼出
                            if(fromOtherPageNumber){
                                callFunction(fromOtherPageNumber);
                                sessionStorage.removeItem('callNumber');
                            }
                        }
                    }
                },
                error: function(err){
                    ws='';
                    window.ws=ws;
                    $('.user-name-word').html('<span data-fn="open-ztphone" style="color:#e7505a;" class="tooltip-test" data-toggle="tooltip" data-placement="right" title="若已安装可点击打开">请先打开软化机</span>');
                    setTimeout(()=>{
                        initPing();
                    },2000)
                }
            })
        }

        async function createWebSocket(){
            if ('WebSocket' in window){
                ws = new WebSocket(wsUrl);
                window.ws=ws;
                socketPhoneStatus();
            }else{
                toastr.error('您的浏览器不支持WebSocket，无法使用电话业务');
            }
        }
        async function socketPhoneStatus(){
            ws.onmessage = async function (event) {
                try {
                    var res = JSON.parse(event.data)
                }catch(e) {
                    console.log('接收数据格式错误');
                }
                console.log(res)

                let number= res.phone||'';
                if(res.error){
                    //呼叫失败
                    toastr.error(res.error);
                }else if(number){
                    if(!res.callin){
                        //呼出相关的
                        if(res.status=='begincall'){
                            communicateCall({
                                phone: number,
                                callid: res.uuid,
                                caseId: $('[name="caseId"]').val(),
                            })
                        }
                        if(res.status=='begincall'||res.status=='earlymedia'){
                            //呼出响铃
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'接通中…');
                            $('[data-fn="hangup"]').show();
                            $('[data-hover="call"]').hide();
                        }else if(res.status=='incalling'){
                            //呼出电话接通
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已接通');
                            $('[data-fn="hangup"]').show();
                            $('[data-hover="call"]').hide();
                            clearInterval(callOut_timer);
                            clearInterval(callIn_timer);
                            callOut_timer = callOutTimer();
                        }else if(res.status=='hangup'){
                            callStatus=false;
                            //呼出电话接通
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                            $('[data-fn="hangup"]').hide();
                            $('[data-hover="call"]').show();
                            clearInterval(callOut_timer);
                            clearInterval(callIn_timer);
                        }
                    }else{
                        //呼入相关的
                        if(res.status=='ring'){
                            //呼入响铃
                            $('#callInModal').modal();
                            $('[data-ele="callIn-phone"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'接通中…');
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'接通中…');
                            $('[data-fn="answer"]').show();
                            $('[data-fn="hangup"]').show();
                            callid= res.uuid;
                            nowPhone = number;
                            await searchCasein(number);
                            $('[name="callId"]').val(res.uuid);
                        }else if(res.status=='incalling'){
                            //呼入电话接通
                            $('[data-ele="callIn-phone"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已接通');
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已接通');
                            $('[data-fn="answer"]').hide();
                            $('[data-fn="hangup"]').show();
                            clearInterval(callIn_timer);
                            clearInterval(callOut_timer);
                            callIn_timer = callInTimer();
                            callOut_timer = callOutTimer();
                            $('[name="callId"]').val(res.uuid);
                        }else if(res.status=='hangup'){
                            callStatus=false;
                            //呼入电话接通
                            $('[data-ele="callIn-phone"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                            $('[data-fn="answer"]').hide();
                            $('[data-fn="hangup"]').hide();
                            $('[data-fn="hangup"]').hide();
                            $('[data-hover="call"]').show();
                            clearInterval(callIn_timer);
                            clearInterval(callOut_timer);
                            $('[name="callId"]').val(res.uuid);
                        }
                    }
                }else{
                    //突然软件出问题
                    ws && ws.close && ws.close();
                    initPing();
                }

            }
        }

        if(calljumpInfo){
            calljumpInfo=JSON.parse(calljumpInfo);
            sessionStorage.removeItem('calljumpInfo');
            clearInterval(callOut_timer);
            if(calljumpInfo.callInTimer){
                $('[data-ele="phone-text-status"]').html(calljumpInfo.phone.substring(0,3)+'****'+calljumpInfo.phone.substring(calljumpInfo.phone.length-4,calljumpInfo.phone.length)+'呼入');
                $('[data-fn="hangup"]').show();
                $('[data-hover="call"]').hide();
                callOut_timer = callOutTimer(
                    calljumpInfo.callInTimer.substring(0,2),
                    calljumpInfo.callInTimer.substring(3,5),
                    calljumpInfo.callInTimer.substring(6,8),
                );
            }
            $('[name="callId"]').val(calljumpInfo.callid);
        }

        function callOutTimer(h,m,s) {
            //秒
            var n_sec = s||0;
            //分
            var n_min = m||0;
            //时
            var n_hour = h||0;
            return setInterval(function () {
                n_sec++;
                if (n_sec > 59) {
                    n_sec = 0;
                    n_min++;
                }
                if (n_min > 59) {
                    n_sec = 0;
                    n_hour++;
                }
                var str_sec = n_sec;
                var str_min = n_min;
                var str_hour = n_hour;
                if (n_sec < 10) {
                    str_sec = "0" + n_sec;
                }
                if (n_min < 10) {
                    str_min = "0" + n_min;
                }
                if (n_hour < 10) {
                    str_hour = "0" + n_hour;
                }
                var time = str_hour + ":" + str_min + ":" + str_sec;
                $('.callOutTimer').html(time)
            }, 1000);
        }
        function callInTimer() {
            //秒
            var n_sec = 0;
            //分
            var n_min = 0;
            //时
            var n_hour = 0;
            return setInterval(function () {
                n_sec++;
                if (n_sec > 59) {
                    n_sec = 0;
                    n_min++;
                }
                if (n_min > 59) {
                    n_sec = 0;
                    n_hour++;
                }
                var str_sec = n_sec;
                var str_min = n_min;
                var str_hour = n_hour;
                if (n_sec < 10) {
                    str_sec = "0" + n_sec;
                }
                if (n_min < 10) {
                    str_min = "0" + n_min;
                }
                if (n_hour < 10) {
                    str_hour = "0" + n_hour;
                }
                var time = str_hour + ":" + str_min + ":" + str_sec;
                $('.callInTimer').html(time)
            }, 1000);
        }
        async function callFunction(number){
            {if !$workerId}
            toastr.error('暂无权限');
            return false;
            {/if}
            if(!ws){
                toastr.error('电话初始失败，请稍后再试');
                return false;
            }
            if(!callStatus){
                toastr.error('正在呼叫中，请稍后再试');
                return false;
            }
            callStatus=true;
            let res = await ajaxPromise({
                url: http_url+'/call',
                method: "get",
                data: {
                    number: number,
                    callid:'',
                },
            })
            if(res.code==200){
                callid= res.callid;
                nowPhone = number;
                $('[name="callId"]').val(res.callid);
            }
        }
        async function answerFunction(){
            let res = await ajaxPromise({
                url: http_url+'/answer',
                method: "get",
                data: {},
            })
        }
        async function hangupFunction(){
            let res = await ajaxPromise({
                url: http_url+'/hangup',
                method: "get",
                data: {},
            })
        }

        async function communicateCall(json){
            ajaxPromise({
                url: '/callinfo/call',
                method: "post",
                data: {
                    caseId: json.caseId,
                    phone: json.phone,
                    uuid: '',
                    callId: json.callid
                },
            })
        }
        async function searchCasein(search){
            let res= await ajaxPromise({
                url:"/callinfo/searchCasein",
                method: "post",
                data: {
                    search: search,
                },
            })
            if(res.code==200){
                if(res.data.length){
                    let hml='';
                    $.each(res.data,function(index,val){
                        hml+=`
                            <tr>
                                <td>${
                                    val.litigantName
                                }</td>
                                <td>${
                                    val.cardId
                                }</td>
                                <td>${
                                    val.mediateNum
                                }</td>
                                <td>
                                    <a href="/mediate/detail?caseId=${
                                        val.caseId
                                    }" 
                                    data-caseId="${
                                        val.caseId
                                    }"
                                    data-telephone="${
                                        nowPhone
                                    }"
                                    data-callid="${
                                        callid
                                    }"
                                    data-ele="jump-detal"
                                    >详情</a>
                                </td>
                            </tr>
                        `;
                    })
                    $('.case-tbody').html(hml);
                }else{
                    $('.case-tbody').html('未查询到数据');
                }
            }else{
                toastr.error(res.message);
            }
        }
    
    })

</script>